#!/user/bin/env set PYTHONIOENCODING=utf-8 && python -u
# -*- coding: utf-8 -*-

import os
import codecs

from util.json import JSON
from util.dictionaries import PropertyLikeDict

class Settings(object):
    '''
    默认设置
    '''

    @property
    def output_directory(self): return os.path.join(self.current_work_directory, self['output_directory'])

    @output_directory.setter
    def output_directory(self, output_directory): self.__data__['output_directory'] = output_directory

    def __init__(self):
        '''
        加载设置
        '''
        self.current_work_directory = os.getcwd()
        self.settings_json_file = os.path.join(self.current_work_directory, 'settings.json')
        if not os.path.isfile(self.settings_json_file):
            raise Exception(f'File not found: {self.settings_json_file}')
        with codecs.open(self.settings_json_file, 'r', 'utf-8') as fp:
            json_text = fp.read()
            self.__data__ = PropertyLikeDict(JSON.parse(json_text))

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, 'instance'):
            cls.instance = super(Settings, cls).__new__(cls, *args, **kwargs)
        return cls.instance

    def __getitem__(self, path=None):
        '''
        获取设置
        @path `user.idcard.idnumber` | `users[1].idcard.idnumber`
        '''
        return self.__data__[path]

    def __contains__(self, path=None):
        return self[path] is not None
